package com.lokiy.core.adapter

import androidx.viewbinding.ViewBinding


/**
 * LifecycleLoadMoreAdapter
 *
 * @author Lokiy
 * @date 2023/4/6 13:30
 */
open class LifecycleLoadMoreAdapter<T, Binding : ViewBinding>(
    private val pageSize: Int = 20,
    private val onLoadMore: () -> Unit = {},
    private val onViewRecycled: (LifecycleBindingHolder<Binding>) -> Unit = {},
    private val onBindHolder: LifecycleViewBindingAdapter<T, Binding>.(LifecycleBindingHolder<Binding>, T) -> Unit,
) : LifecycleViewBindingAdapter<T, Binding>() {
    private var isOnLoadMore = false
    private var isLoadEnd = false

    override fun onBindViewHolder(holder: LifecycleBindingHolder<Binding>, item: T?) {
        item ?: return
        onBindHolder.invoke(this, holder, item)
    }

    override fun getItemViewType(position: Int): Int {
        if (position >= itemCount - 2 && isOnLoadMore.not() && isLoadEnd.not()) {
            isOnLoadMore = true
            onLoadMore.invoke()
        }
        return super.getItemViewType(position)
    }

    override fun onViewRecycled(holder: LifecycleBindingHolder<Binding>) {
        super.onViewRecycled(holder)
        onViewRecycled.invoke(holder)
    }

    override fun addAll(list: Collection<T>?) {
        isOnLoadMore = false
        isLoadEnd = (list?.size ?: 0) < pageSize
        super.addAll(list)
    }

    override fun refresh(list: Collection<T>?) {
        isOnLoadMore = false
        isLoadEnd = (list?.size ?: 0) < pageSize
        super.refresh(list)
    }

    override fun notifyChanged(list: Collection<T>?) {
        isOnLoadMore = false
        isLoadEnd = (list?.size ?: 0) < pageSize
        super.notifyChanged(list)
    }
}